package com.xjoyt.pay.master.services;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.commons.PayTypeUtils;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.master.po.Merchant;
import com.xjoyt.pay.master.po.MerchantChannel;
import com.xjoyt.pay.master.po.MerchantChannelRate;
import com.xjoyt.pay.master.repository.MerchantChannelRateRepository;
import com.xjoyt.pay.master.repository.MerchantChannelRepository;
import com.xjoyt.pay.master.repository.MerchantRepository;
import com.xjoyt.pay.master.vo.MerchantChannelMap;
import com.xjoyt.pay.master.vo.MerchantRateMap;
import com.xjoyt.pay.master.vo.RateEntry;

@Service
public class MerchantChannelRateService {

	@Autowired
	private MerchantChannelRateRepository repository;

	@Autowired
	private MerchantRepository merchantRepository;

	@Autowired
	private MerchantChannelRepository merchantChannelRepository;

	public ExecuteResult<?> save(MerchantChannelMap param) {

		for (RateEntry item : param.rateList) {
			if (StringUtils.isBlank(PayTypeUtils.getName(item.type)))
				continue;
			MerchantChannelRate entity = new MerchantChannelRate();
			entity.type = item.type;
			entity.rate = item.rate;
			entity.merchantChannel = param;
			repository.save(entity);
		}

		return ExecuteResult.ok();
	}

	public ExecuteResult<?> saveRateForAll(MerchantRateMap param) {

		Merchant merchant = merchantRepository.findOne(param.id);
		if (merchant == null) {
			return ExecuteResult.fail("数据不存在");
		}
		List<MerchantChannel> list = merchantChannelRepository.findAllByMerchantId(merchant.id);
		if (CollectionUtils.isEmpty(list)) {
			return ExecuteResult.fail();
		}
		for (MerchantChannel merchantChannel : list) {
			repository.findAllByMerchantChannelId(String.valueOf(merchantChannel.id)).forEach(item -> repository.delete(item));
			if (CollectionUtils.isEmpty(param.rateList)) {
				return ExecuteResult.fail();
			}
			for (RateEntry item : param.rateList) {
				if (StringUtils.isBlank(PayTypeUtils.getName(item.type)))
					continue;
				MerchantChannelRate entity = new MerchantChannelRate();
				entity.type = item.type;
				entity.rate = item.rate;
				entity.merchantChannel = merchantChannel;
				repository.save(entity);
			}
		}
		return ExecuteResult.ok();
	}
}
